package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpUrlConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.quartz.domain.StockBasic;
import com.ruoyi.quartz.domain.StockRealTime;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.mapper.StockBasicMapper;
import com.ruoyi.quartz.mapper.StockRealTimeMapper;
import com.ruoyi.quartz.mapper.SysJobMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

@Component("stockTask")
public class StockTask {

    @Resource
    private StockRealTimeMapper stockRealTimeMapper;

    @Resource
    private SysJobMapper sysJobMapper;

    @Resource
    private StockBasicMapper stockBasicMapper;

    public void insertStockRealJob(String hour,Integer minute){

        SysJob sysJob = null;

        StockBasic sb = new StockBasic();
        sb.setIsHs300("Y");
        sb.setMarket("主板");
        List<StockBasic> list = stockBasicMapper.selectStockBasicList(sb);
        String invokeTarget = "";
        String cronExpression = "";
        int second = 0;
        for(StockBasic stockBasic:list){
            invokeTarget = "stockTask.realTimeTrade('stockCode','exchange')";
            cronExpression = "second minute hour * * ?";
            cronExpression = cronExpression.replaceAll("second",String.valueOf(second));
            cronExpression = cronExpression.replaceAll("minute",String.valueOf(minute));
            cronExpression = cronExpression.replaceAll("hour",hour);
            sysJob = new SysJob();
            sysJob.setJobGroup("STOCK");
            sysJob.setJobName(stockBasic.getName()+"实时采集");
            sysJob.setCronExpression(cronExpression);
            sysJob.setMisfirePolicy("1");
            sysJob.setConcurrent("1");
            sysJob.setStatus("0");
            invokeTarget = invokeTarget.replaceAll("stockCode",stockBasic.getSymbol());
            invokeTarget = invokeTarget.replaceAll("exchange",stockBasic.getExchange());
            sysJob.setInvokeTarget(invokeTarget);
            sysJobMapper.insertJob(sysJob);
            second+=4;
            if (second>59){
                second = 0;
                minute+=1;
            }
        }
    }

    public void  realTimeTrade (String stockCode,String exchange){

        if (!stockBasicMapper.getTradeDateCount(DateUtils.dateTime())){
            return;
        }

        StringBuilder code = new StringBuilder();
        String url = "";
        String s = "";
        String[] temps;
        double price = 0;
        long vols = 0;
        long vol = 0 ;
        StockRealTime stockRealTime = null;

        JSONObject data = null;
        JSONObject tmp = null;
        JSONArray jsonArray = null;
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        long startMillis = System.currentTimeMillis();
        long overMillis = 0l;
        if ("SSE".equals(exchange)){
            code.append("1.").append(stockCode);
        }else{
            code.append("0.").append(stockCode);
        }
        url = HttpUrlConstants.EAST_STOCK_REAL_TIME_TRADE_URL.replaceAll("tsCode",code.toString());
        System.out.println(url);
        List<StockRealTime> stockRealTimes = new ArrayList<>();
        try{
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Constants.UTF8));
            String line;

            while ((line = in.readLine()) != null)
            {
                if ("".equals(line)){
                    tmp = JSON.parseObject(result.substring(result.indexOf("{")));
                    data = tmp.getJSONObject("data");
                    if (data!=null){
                        jsonArray = data.getJSONArray("details");
                        for (int i=0;i<jsonArray.size();i++){
                            stockRealTime = new StockRealTime();
                            s = jsonArray.getString(i);
                            temps = s.split(",");
                            price = Double.parseDouble(temps[1]);
                            vol = Long.parseLong(temps[2]);
                            vols += vol;
                            stockRealTime.setDealTime(temps[0]);
                            stockRealTime.setDealPrice(BigDecimal.valueOf(price));
                            stockRealTime.setDealVolume(vol);
                            stockRealTime.setDealType(temps[4]);
                            stockRealTime.setSymbol(stockCode);
                            stockRealTime.setDealDate(DateUtils.dateTime());
                            stockRealTimes.add(stockRealTime);
                            if (stockRealTimes.size()==20){
                                stockRealTimeMapper.batchInsertStockRealTime(stockRealTimes);
                                stockRealTimes.clear();
                            }
                        }
                        if (stockRealTimes.size()>0){
                            stockRealTimeMapper.batchInsertStockRealTime(stockRealTimes);
                            stockRealTimes.clear();
                        }


                    }
                    result.delete(0,result.length());
                    continue;
                }
                result.append(line);

                overMillis = System.currentTimeMillis();
                if (overMillis - startMillis > 25200000){
                    throw new RuntimeException(stockCode+ " 今日结束");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }

    }

}
